package concurrensy.connection_pool;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class MyConnectionManager {

	private static final long CLEAN_PERIOD = 1000;
	private ConnectionPool connectionPool;
	private long lastPoolClean = System.currentTimeMillis();
	private List<Connection> connectionList = new ArrayList<>();

	public MyConnectionManager(String url, String user, String password) {
		connectionPool = new ConnectionPoolImpl(url, user, password);
	}

	public Connection getConnection() throws SQLException {
		if ((System.currentTimeMillis() - lastPoolClean) > CLEAN_PERIOD) {
			returnNonActiveConnections();
			lastPoolClean = System.currentTimeMillis();
		}
		Connection result = connectionPool.checkout();
		connectionList.add(result);
		return result;
	}

	private void returnNonActiveConnections() {
		for (Connection conn : connectionList) {
			MyConnection connection = (MyConnection) conn;
			if (ConnectionPool.IDLE_TIMEOUT > connection.getNotActiveTime()) {
				connectionPool.checkin(conn);
			}
		}
	}

	public void close(Connection conn) {
		if ((System.currentTimeMillis() - lastPoolClean) > CLEAN_PERIOD) {
			returnNonActiveConnections();
			lastPoolClean = System.currentTimeMillis();
		}
		connectionPool.checkin(conn);
	}
}
